//
// Created by QU on 24-8-18.
//

#include <filesystem>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

int main(int argc, char* argv[])
{
    try
    {
        if (argc != 2)
        {
            std::cerr << "Usage: " << std::filesystem::path(argv[0]).filename() << " <host>" << std::endl;
            return 1;
        }

        // executor
        auto io_context { boost::asio::io_context() };

        auto resolver = udp::resolver(io_context);
        udp::endpoint reciver_endpoint = *(resolver.resolve(udp::v4(), argv[1], "daytime").begin());

        /*
        for (auto it = endpoints.begin(); it != endpoints.end(); ++it)
        {
            std::cout << it->endpoint() << std::endl;
        }
        std::cout << std::endl;
        */

        auto udp_socket { udp::socket(io_context) };
        auto error_code { boost::system::error_code() };
        udp_socket.open(udp::v4(), error_code);

        std::array<char, 1> send_buffer { 0 };
        udp_socket.send_to(boost::asio::buffer(send_buffer), reciver_endpoint);

        // 现在我们需要准备好接受服务器发回给我们的任何东西。我们这边接收服务器响应的端点将由 ip::udp::socket::receive_from（） 初始化。
        std::array<char, 128> recv_buffer;
        udp::endpoint sender_endpoint;
        size_t recived_size = udp::socket::receive_from(boost::asio::buffer(recv_buffer), sender_endpoint);

        std::cout.write(recv_buffer.data(), recived_size);
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}
